var app = getApp();
var time = require('../../utils/util.js');
Page({
  data: {
    getAllBooks: app.globalData.bookUrl + '/book/getBooks.do', //获取所有图书信息
    register: app.globalData.bookUrl + '/user/userRegister.do', //注册
    userInfo: app.globalData.bookUrl + '/user/userInfo.do', //判断是否已注册
    getBookType: app.globalData.bookUrl + '/book/bookType.do', //获取图书类别
    getLoseBookURL: app.globalData.bookUrl + '/user/getLoseBook.do', //获取图书类别
    getopenidN: app.globalData.bookUrl + '/WXAppletUserInfo/code.do',
    getBorrowingsURL: app.globalData.bookUrl + '/Borrowing/getBorrowingsall.do',//借阅记录
    winWidth: 0,
    winHeight: 0,
    currentTab: 0,
    totalElements: 0,
    borrowingsTotalElements:0,
    losttotalElements: 0,
    currentPage: 1,
    borrowingsCurrentPage: 1,
    // borrowingsCurrentPageThirty: 1,
    sumlist: [],
    withoutlist: [],
    sumBorrowingsList:[],
    sumBorrowingsListThirty:[],
    height: 0
  },
  onLoad: function(options) {
    var that = this;
    /** 获取系统信息 */
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    var query = wx.createSelectorQuery();
    query.select('.libruary').boundingClientRect()
    query.exec(function(res) {
      console.log(res[0].height);
      that.setData({
        height: res[0].height
      })
    });
    wx.login({
      success: function(res) {
        //发起网络请求 
        wx.request({
          url: that.data.getopenidN,
          data: {
            code: res.code
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          method: 'POST',
          //服务端的回掉 
          success: function(result) {
            wx.setStorage({
              key: "openid",
              data: result.data.openid
            })
            that.setData({
              openId: result.data.openid
            });
            that.getuserInfo();
          }

        })
      }
    });
    var getAllBooks = that.data.getAllBooks; //获取图书URL
    var getLoseBookURL = that.data.getLoseBookURL;
    that.getBookType(that.data.getBookType); //获取全部类别
    this.getAllBooks(getAllBooks, that.data.currentPage); //获取全部图书
    this.getBorrowings(that.data.getBorrowingsURL, that.data.borrowingsCurrentPage);
    // this.getBorrowingsThirty(that.data.getBorrowingsURL, that.data.borrowingsCurrentPageThirty);


  },
  onShow: function() {
    app.scanFlag = true
    // var that = this
    // wx.getStorage({
    //   key: 'openid',
    //   success(res) {
    //     // that.setData({
    //     //   openId: res.data
    //     // });
    //     wx.showToast({
    //       title: res.data,
    //       icon: "success",
    //       duration: 300
    //     });
    //   }
    // })
    // that.getuserInfo();


  },
  // 下拉刷新
  onPullDownRefresh: function () {
    var that = this;
    // 显示顶部刷新图标
    wx.showNavigationBarLoading({
      title: '正在刷新',
    })
    // 页数+1
    if (that.data.currentTab == 0) {
      that.setData({
        sumBorrowingsList: [],
        sumBorrowingsListThirty: [],
      });
      that.getBorrowings(that.data.getBorrowingsURL, 1);//借阅动态
    }else if (that.data.currentTab == 1) {//上架
      that.setData({
        sumlist: [],
      });
      that.getAllBooks(that.data.getAllBooks, 1);
    }else{
      that.setData({
        withoutlist: [],
      });
      that.getLoseBooks(that.data.getLoseBookURL, 3, 1); //获取丢失图书
  }
  },
  lower: function() {
    var that = this;
    var sumlistResult = that.data.sumlist;
    var sumBorrowingsListResult = that.data.sumBorrowingsList.length;
    var sumBorrowingsListThirtyResult = that.data.sumBorrowingsListThirty.length;
    var lowNum = parseInt(sumBorrowingsListResult) +parseInt(sumBorrowingsListThirtyResult)
    if (that.data.currentTab == 0) {//借阅动态
      if (lowNum == that.data.borrowingsTotalElements) { //最大数值
        wx.showToast({
          title: "已到达底部",
          icon: "success",
          duration: 300
        });
        return false;
      } else {
        // 显示加载图标
        // wx.showLoading({
        //   title: '玩命加载中',
        // })
        // 页数+1
        that.getBorrowings(that.data.getBorrowingsURL, that.data.borrowingsCurrentPage);//借阅动态

      }
    }
    if (that.data.currentTab == 1){//上架
      if (sumlistResult.length == that.data.totalElements) { //最大数值
        wx.showToast({
          title: "已到达底部",
          icon: "success",
          duration: 300
        });
        return false;
      } else {
        // 显示加载图标
        // 页数+1
        that.getAllBooks(that.data.getAllBooks, that.data.currentPage);
      
        }
    }else{
      that.getLoseBooks(that.data.getLoseBookURL, 3, that.data.currentPage); //获取丢失图书
    }
    
    
  },
  // getOpenId: function(code) {
  //   var that = this;
  //   wx.request({
  //     url: "https://api.weixin.qq.com/sns/jscode2session?appid=" +
  //       app.globalData.appid + "&secret=" + app.globalData.secret +
  //       "&js_code=" + code + "&grant_type=authorization_code",
  //     data: {},
  //     method: 'GET',
  //     success: function(res) {
  //       var openid = res.data.openid
  //       wx.setStorage({
  //         key: "openid",
  //         data: openid
  //       })
  //       wx.showToast({
  //         title: res.data.openid,
  //         icon: 'success',
  //         duration: 5000
  //       })
  //       that.setData({
  //         openId: res.data.openid
  //       });

  //       that.getuserInfo(); //判断是否注册
  //     },
  //     fail: function() {
  //       // fail   
  //     },
  //     complete: function() {
  //       // complete   
  //     }
  //   })
  // },
  getuserInfo: function() {
    var that = this;

    wx.request({
      url: that.data.userInfo,
      data: {
        openId: that.data.openId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        if (res.data.data.content == 0) {
          that.userRegister(); //只注册openid信息
        } else {
          console.log("欢迎")
        }
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
  },
  userRegister: function() {
    var that = this;
    wx.request({
      url: that.data.register,
      data: {
        openId: that.data.openId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log("注册成功")
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
  },
  getAllBooks: function(getAllBooks, currentPage) {
    var that = this;
    wx.request({
      url: getAllBooks,
      data: {
        currentPage: currentPage
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log(res.data.data)
        that.showAllBooks(res.data.data); //向前台传递数据
        if (res.data.data != null) {
          that.setData({
            currentPage: currentPage + 1,
            totalElements: res.data.data.totalElements
          });
        }

      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  getLoseBooks: function(getLoseBookURL, bookState, currentPage) {
    var that = this;
    wx.request({
      url: getLoseBookURL,
      data: {
        bookState: bookState,
        currentPage: currentPage
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        that.showLoseBooks(res.data.data); //向前台传递数据
        if (res.data.data != null) {
          that.setData({
            currentPage: currentPage + 1,
            losttotalElements: res.data.data.length
          });
        }

      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  getBorrowings: function (getBorrowings, borrowingsCurrentPage) {
    var that = this;
    wx.request({
      url: getBorrowings,
      data: {
        currentPage: borrowingsCurrentPage
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res.data.data)
        that.showAllBorrowingsBooks(res.data.data); //向前台传递数据
        if (res.data.data != null) {
          that.setData({
            borrowingsCurrentPage: borrowingsCurrentPage + 1,
            borrowingsTotalElements: res.data.data.pageInfo.totalElements
          });
        }

      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
// getBorrowingsThirty: function (getBorrowingsThirty, borrowingsCurrentPageThirty) {
//     var that = this;
//     wx.request({
//       url: getBorrowingsThirty,
//       data: {
//         borrowingState30: 2,
//         currentPage: borrowingsCurrentPageThirty
//       },
//       method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
//       header: {
//         "Content-Type": "application/x-www-form-urlencoded"
//       },
//       success: function (res) {
//         console.log(res.data.data)
//         that.showAllBorrowingsBooksThirty(res.data.data); //向前台传递数据
//         if (res.data.data != null) {
//           that.setData({
//             borrowingsCurrentPageThirty: borrowingsCurrentPageThirty + 1,
//             borrowingsThirtyTotalElements: res.data.data.totalElements
//           });
//         }

//       },
//       fail: function (error) {
//         // fail
//         console.log(error)
//       }
//     })
//   },
  
  getBookType: function(getBookType) {
    var that = this;
    wx.request({
      url: getBookType,
      data: {},
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log(res);
        that.showBookType(res.data.data); //向前台传递数据
        that.getLoseBooks(that.data.getLoseBookURL, 3, that.data.currentPage); //获取丢失图书
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
  },
  showBookType: function(allBookType) {
    var that = this;
    var bookType = [];
    bookType.push("全部");
    if (allBookType.size > 0) {
      for (var idx in allBookType.content) {
        var content = allBookType.content[idx];
        var bookTypeName = content.bookTypeName;
        bookType.push(bookTypeName);
        that.setData({
          bookTypeList: bookType
        });
      }
    } else {
      console.log("没有该分类");
    }
  },
  showAllBooks: function(allBooks) {
    var books = this.data.sumlist;
    if (allBooks != null) {
      for (var idx in allBooks.content) {
        var content = allBooks.content[idx];
        var bookImgSource = app.globalData.bookUrl + content.bookImg+'?'+Math.random() / 9999;
        var createTimeSource = time.formatTime(content.createTime, 'Y-M-D h:m:s');
        var temp = {
          bookImg: bookImgSource,
          bookName: content.bookName,
          createTime: createTimeSource,
        }
        books.push(temp);

      }
      this.setData({
        sumlist: books
      });
      wx.hideLoading({
        title: '玩命加载中',
      })
    } else {
      wx.showToast({
        title: "没有更多了",
        icon: "success",
        duration: 1500
      })
    }
  },

  showLoseBooks: function(allLoseBooks) {
    var that = this;
    var books = this.data.withoutlist;
    if (allLoseBooks != null) {
      for (var idx in allLoseBooks) {
        var content = allLoseBooks[idx];
        var bookImgSource = app.globalData.bookUrl + content.bookImg;
        var borrowingTimeSource = "";
        if (content.returnedTime != null) {
          borrowingTimeSource = time.formatTime(content.returnedTime, 'Y-M-D h:m:s')
        } else if (content.borrowingTime != null) {
          borrowingTimeSource = time.formatTime(content.borrowingTime, 'Y-M-D h:m:s');
        }
        var bookTypeIdSource = content.bookTypeId;
        var types = that.data.bookTypeList;
        var typeName = types[bookTypeIdSource];
        var temp = {
          bookImg: bookImgSource,
          bookName: content.bookName,
          bookType: typeName,
          borrowingTime: borrowingTimeSource,
          bookAuthor: content.bookAuthor
        }
        books.push(temp);
        that.setData({
          withoutlist: books
        });
      }
      wx.hideLoading({
        title: '玩命加载中',
      })
    } else {
      console.log("没有丢失");
    }
  },
  showAllBorrowingsBooks: function (allBorrowingsBooks) {
    var that = this ;
    var books = that.data.sumBorrowingsList;
    var exceedThirtybooks = that.data.sumBorrowingsListThirty;
    if (allBorrowingsBooks.borrowinglist1 != null || allBorrowingsBooks.borrowinglist2 != null) {
    if (allBorrowingsBooks.borrowinglist1 != null ) {
      for (var idx in allBorrowingsBooks.borrowinglist1) {
        var content = allBorrowingsBooks.borrowinglist1[idx];
        var borrowingTime = time.formatTime(content.createTime, 'Y-M-D h:m:s');
        var borrowingState = content.borrowingState;
        // var nowDate = time.nowFormatTime(new Date());
        // var borrow_date = new Date(borrowingTime.replace(/-/g, "/"));
        // var now_date = new Date(nowDate.replace(/-/g, "/"));
        // var days = now_date.getTime() - borrow_date.getTime();
        // var day = parseInt(days / (1000 * 60 * 60 * 24)) + 1;
        // if (day > 30 && borrowingState==2){
          var exceedThirtyTemp = {
            readersName: content.readersName,
            bookName: content.bookName,
            borrowingState: borrowingState,
            borrowingTime: borrowingTime,
            headImg:content.headImg,
          }
          exceedThirtybooks.push(exceedThirtyTemp);
        // }else{
      }
    } 
      if (allBorrowingsBooks.borrowinglist2 != null) {
        for (var idx in allBorrowingsBooks.borrowinglist2) {
          var content = allBorrowingsBooks.borrowinglist2[idx];
          var borrowingTime = time.formatTime(content.createTime, 'Y-M-D h:m:s');
          var borrowingState = content.borrowingState;
          // var nowDate = time.nowFormatTime(new Date());
          // var borrow_date = new Date(borrowingTime.replace(/-/g, "/"));
          // var now_date = new Date(nowDate.replace(/-/g, "/"));
          // var days = now_date.getTime() - borrow_date.getTime();
          // var day = parseInt(days / (1000 * 60 * 60 * 24)) + 1;
          // if (day > 30 && borrowingState==2){
          var temp = {
            readersName: content.readersName,
            bookName: content.bookName,
            borrowingState: borrowingState,
            borrowingTime: borrowingTime,
            headImg: content.headImg,
          }
          books.push(temp);
        }
        
      }
      that.setData({
        sumBorrowingsList: books,
        sumBorrowingsListThirty: exceedThirtybooks
      });
      wx.hideLoading({
        title: '玩命加载中',
      })
    } else {
      wx.showToast({
        title: "没有更多了",
        icon: "success",
        duration: 1500
      })
    }
  },
  // showAllBorrowingsBooksThirty: function (allBorrowingsBooksThirty) {
  //   var exceedThirtybooks = this.data.sumBorrowingsListThirty;
  //   if (allBorrowingsBooksThirty != null) {
  //     for (var idx in allBorrowingsBooksThirty.content) {
  //       var content = allBorrowingsBooksThirty.content[idx];
  //       var borrowingTime = time.formatTime(content.borrowingTime, 'Y-M-D h:m:s');
  //         var exceedThirtyTemp = {
  //           readersName: content.readersName,
  //           bookName: content.bookName,
  //           borrowingState: content.borrowingState,
  //           borrowingTime: borrowingTime,
  //         }
  //         exceedThirtybooks.push(exceedThirtyTemp);
  //     }
  //     this.setData({
  //       sumBorrowingsListThirty: exceedThirtybooks
  //     });
  //     wx.hideLoading({
  //       title: '玩命加载中',
  //     })
  //   } else {
  //     wx.showToast({
  //       title: "没有更多了",
  //       icon: "success",
  //       duration: 1500
  //     })
  //   }
  // },
  bindChange: function(e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });

  },
  swichNav: function(e) {

    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  }
})